import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Layout from '../views/Layout.vue'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Home',
        component: Home
      },
      {
        path: 'product-category',
        name: 'ProductCategoryList',
        component: () => import('../views/ProductCategoryList.vue')
      },
      {
        path: 'user-category',
        name: 'UserCategoryList',
        component: () => import('../views/UserCategoryList.vue')
      },
       {
        path: 'product',
        name: 'ProductList',
        component: () => import('../views/ProductList.vue')
      },
      {
        path: 'order',
        name: 'OrderList',
        component: () => import('../views/OrderList.vue')
      },
       {
        path: 'user',
        name: 'UserList',
        component: () => import('../views/UserList.vue')
      },
      // 其他业务页面可在此添加
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫：未登录跳转登录页
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const role = localStorage.getItem('role')
  if (to.path !== '/login' && (!token || role !== 'admin')) {
    // 未登录或不是admin，强制跳转登录页
    next('/login')
  } else if (to.path === '/login' && token && role === 'admin') {
    // 已登录且是admin，访问登录页时跳转首页
    next('/')
  } else {
    next()
  }
})

export default router
